from django.db import models
from django.contrib.contenttypes import generic
from base import DataItem, Type, TimeRelation

class Person(models.Model):
    '''
    A person that plays a role in a described political system
    '''
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    slug = models.SlugField()
    data = generic.GenericRelation(DataItem)

    class Meta:
        ordering = ('last_name', 'first_name')
        verbose_name_plural = 'People'
        app_label = 'openpolitics'

    def get_name(self):
        return '%s %s' % (self.first_name, self.last_name)

    name = property(get_name)

    __unicode__ = get_name

class Deputy(Person):
    class Meta:
        proxy = True

    @property
    def img(self):
        try:
            return self.data.get(type__name='img_url').value
        except:
            pass
        try:
            return self.data.get(type__name='source_sejmgovpl_img_url').value
        except:
            pass
        try:
            return self.data.get(type__name='source_senatgovpl_img_url').value
        except:
            pass
        

    @property
    def list_positions(self):
        positions = self.positions.select_related(depth=2).all()
        return ', '.join(map(lambda x:x.__unicode__(), positions))

    @property
    def party_affiliation(self):
        # super slow, we have to fix that, selected_related doesn't help unfortunately :(
        from openpolitics.models.structures import InstitutionType, PositionType, Institution
        party_type = InstitutionType.cached.lazy_get(name="Party")
        position_type = PositionType.cached.lazy_get(name="Member")
        try:
            party = self.positions.select_related(depth=2).get(type=position_type)
            return party.institution
        except:
            return None